package com.wisdytech.linkdcs.tool.action;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.StandardResult;
import com.wisdytech.common.bean.StandardTableResult;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.ResourceMatchingService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.DateUtil;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.model.ToolCheckItem;
import com.wisdytech.linkdcs.tool.service.IToolCheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhanghailin
 * @since 2018-06-12
 */
@Controller
@RequestMapping("/tool/checkItem")
public class ToolCheckItemAction {

    @Value("${img.localtion}")
    private String fileLocation;


    @Resource
    private IToolCheckItemService toolCheckItemService;
    @Autowired
    @Qualifier("resourceMatchingService")
    private ResourceMatchingService resourceMatchingService;
    /**
     *
     * <p>Description: 设备信息</p>
     * @param model model
     * @return String
     */
    @RequestMapping("/index")
    public String toolCheckItemIndex(Model model, HttpServletRequest httpRequest){
        this.resourceMatchingService.getResourceName(httpRequest,model);
        return "tool/toolCheckItem";
    }

    /**
     * 分页查询接口
     * @param toolCode 必须穿 工装编码
     * @param filter 分页参数
     * @return 分页结果
     */
    @RequestMapping(value = "/getToolCheckItemByFilter/get.mvc")
    @ResponseBody
    public StandardTableResult<ToolCheckItem> getToolCheckItemByFilter(String toolCode, Filter filter) {
        PageInfo<ToolCheckItem> page = this.toolCheckItemService.getToolCheckItemByFilter(toolCode,filter);
        return new StandardTableResult<>(page.getTotal(),page.getList());
    }

    /**
     * 保存/更新工装配置信息
     * @param toolCheckItem 实体类
     * @return StandardResult
     */
    @RequestMapping(value = "/saveOrUpdateToolCheckItem/save.mvc")
    @ResponseBody
    public StandardResult saveOrUpdateToolCheckItem(ToolCheckItem toolCheckItem) {
        SysUser user = BaseUtil.getCurrentUser();
        this.toolCheckItemService.saveOrUpdateCheckItem(toolCheckItem,user);
        return StandardResult.getSuccessResult();
    }

    /**
     *
     * @param pkIds 主键
     * @return StandardResult
     */
    @RequestMapping(value = "/deleteToolCheckItem/del.mvc")
    @ResponseBody
    public StandardResult deleteToolCheckItem(String pkIds) {
        SysUser operator = BaseUtil.getCurrentUser();
        this.toolCheckItemService.deleteToolCheckItem(pkIds,operator);
        return StandardResult.getSuccessResult();
    }

    /**
     *
     * @param pkId 主键
     * @return StandardResult
     */
    @RequestMapping(value = "/getToolCheckItemById/get.mvc")
    @ResponseBody
    public StandardResult getToolCheckItemById(String pkId) {
        ToolCheckItem t = this.toolCheckItemService.getToolCheckItemById(pkId);
        return StandardResult.getSuccessResult(t);
    }

    /**
     * <p>Description: 保存设备对象</p>
     * @param file 设备对象
     * @param request 请求对象
     * @return 处理结果对象
     */
    @RequestMapping(value = "/uploadFile/save.mvc")
    @ResponseBody
    public JSONObject uploadFile(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        if(!file.isEmpty()){
            //文件位置存放在tomcat webapp根目录
            //String rootPath = request.getSession().getServletContext().getRealPath("/")+"document/";
            String rootPath = fileLocation+"/toolcheckitem/";
            String originalFilename = file.getOriginalFilename();
            //文件初始名
            String fileName = file.getOriginalFilename();
            //文件扩展名
            String extendName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            //文件重命名
            String realName = BaseUtil.getUUID()+extendName;
            //文件夹名
            String dirName =  DateUtil.getCurDateDefaultStr()+"/";

            File targetFile = new File(rootPath+dirName, realName);

            if(!targetFile.getParentFile().exists()){
                targetFile.getParentFile().mkdirs();
            }
            //保存
            JSONObject result = new JSONObject();
            result.put("filePath", "toolcheckitem/"+dirName+realName);
            result.put("originalFileName", originalFilename);
            //文件大小单位KB
            long fileSize = file.getSize()/1000;
            if(fileSize==0L) {
                fileSize = 1L;
            }
            result.put("fileSize", fileSize);
            result.put("fileName",realName);
            try {
                file.transferTo(targetFile);
                return result;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new JSONObject();
    }

    /**
     *
     * <p>Description: 下载文件</p>
     * @param pkId 主键
     * @param response 返回
     */
    @RequestMapping(value = "/downloadFile/get.mvc")
    @ResponseBody
    public void download(String pkId, HttpServletRequest request,HttpServletResponse response) {
        ServletOutputStream os = null;
        try {
            //查询文件
            ToolCheckItem  document = this.toolCheckItemService.getToolCheckItemById(pkId);
            if(document == null) {
                throw new ServiceException("下载文件出错");
            }
            //
            String originalFileName = document.getFileName();
            String filePath = document.getFilePath();
            response.setContentType("application/x-download");
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(originalFileName.getBytes("gb2312"), "ISO8859-1"));
            response.setCharacterEncoding("iso-8859-1");
            //设置header jquery 捕获成功标志
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            //String rootPath = request.getSession().getServletContext().getRealPath("/")+"document/";
            String rootPath = fileLocation+"/";
            InputStream inputStream = new FileInputStream(new File(rootPath+filePath));
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("系统异常");
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

